﻿using System;
using System.Windows.Forms;
using System.Management;
using System.Net.NetworkInformation;
using System.Text.RegularExpressions;

namespace WinFormsApp_GetLocalMachineInfo
{
    public partial class Form1 : Form
    {
        ConfigFile cf = ConfigFile.Instanse;

        public Form1()
        {
            InitializeComponent();

        }

        #region 加载配置文件中的信息
        /// <summary>
        /// 加载配置文件中的信息
        /// </summary>
        protected void loadConfig()
        {
            cf.fileName = AppDomain.CurrentDomain.BaseDirectory + "\\config.ini";
            txtIP.Text = cf["ip地址"];
            txtSubMark.Text = cf["子网掩码"];
            txtGateWay.Text = cf["默认网关"];
            txtDNS1.Text = cf["主DNS"];
            txtDNS2.Text = cf["备用DNS"];
        }
        #endregion

        #region 设置ip信息到网卡
        private void btnSettingNetwork_Click(object sender, EventArgs e)
        {

            try
            {
                if (!IsIpaddress(txtIP.Text.Trim()))
                {
                    MessageBox.Show("ip格式不正确！"); return;
                }
                if (!IsIpaddress(txtSubMark.Text.Trim()))
                {
                    MessageBox.Show("子网掩码格式不正确！"); return;
                }
                if (!IsIpaddress(txtGateWay.Text.Trim()))
                {
                    MessageBox.Show("网关格式不正确！"); return;
                }
                if (!IsIpaddress(txtDNS1.Text.Trim()))
                {
                    MessageBox.Show("DNS1格式不正确！"); return;
                }
                if (!IsIpaddress(txtDNS2.Text.Trim()))
                {
                    MessageBox.Show("DNS2格式不正确！"); return;
                }
                string[] ip = new string[] { txtIP.Text.Trim() };
                string[] SubMark = new string[] { txtSubMark.Text.Trim() };
                string[] GateWay = new string[] { txtGateWay.Text.Trim() };
                string[] DNS = new string[] { txtDNS1.Text.Trim(), txtDNS2.Text.Trim() };
                SetIpInfo(ip, SubMark, GateWay, DNS);
                cf["ip地址"] = txtIP.Text.Trim();
                cf["子网掩码"] = txtSubMark.Text.Trim();
                cf["默认网关"] = txtGateWay.Text.Trim();
                cf["主DNS"] = txtDNS1.Text.Trim();
                cf["备用DNS"] = txtDNS2.Text.Trim();
                MessageBox.Show("ip信息设置成功！", "成功提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
            }
            catch (Exception er)
            {
                MessageBox.Show("设置出错：" + er.Message, "出错提示", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        protected void SetIpInfo(string[] ip, string[] SubMark, string[] GateWay, string[] DNS)
        {
            ManagementBaseObject inPar = null;
            ManagementBaseObject outPar = null;
            ManagementClass mc = new ManagementClass("Win32_NetworkAdapterConfiguration");
            ManagementObjectCollection moc = mc.GetInstances();
            foreach (ManagementObject mo in moc)
            {
                if (!(bool)mo["IPEnabled"]) continue;
                inPar = mo.GetMethodParameters("EnableStatic");
                inPar["IPAddress"] = ip;//ip地址
                inPar["SubnetMask"] = SubMark; //子网掩码 
                mo.InvokeMethod("EnableStatic", inPar, null);//执行

                inPar = mo.GetMethodParameters("SetGateways");
                inPar["DefaultIPGateway"] = GateWay; //设置网关地址 1.网关;2.备用网关
                outPar = mo.InvokeMethod("SetGateways", inPar, null);//执行

                inPar = mo.GetMethodParameters("SetDNSServerSearchOrder");
                inPar["DNSServerSearchOrder"] = DNS; //设置DNS  1.DNS 2.备用DNS
                mo.InvokeMethod("SetDNSServerSearchOrder", inPar, null);// 执行
                break; //只设置一张网卡，不能多张。
            }
        }

        #endregion

        #region 从网卡获取ip设置信息
        /// <summary>
        /// 从网卡获取ip设置信息
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnGetFromNetwork_Click(object sender, EventArgs e)
        {
            NetworkInterface[] nics = NetworkInterface.GetAllNetworkInterfaces();
            foreach (NetworkInterface adapter in nics)
            {
                bool Pd1 = (adapter.NetworkInterfaceType == NetworkInterfaceType.Ethernet); //判断是否是以太网连接
                if (Pd1)
                {
                    IPInterfaceProperties ip = adapter.GetIPProperties();     //IP配置信息
                    if (ip.UnicastAddresses.Count > 0)
                    {
                        txtIP.Text = ip.UnicastAddresses[0].Address.ToString();//IP地址
                        txtSubMark.Text = ip.UnicastAddresses[0].IPv4Mask.ToString();//子网掩码

                    }
                    if (ip.GatewayAddresses.Count > 0)
                    {
                        txtGateWay.Text = ip.GatewayAddresses[0].Address.ToString();//默认网关
                    }
                    int DnsCount = ip.DnsAddresses.Count;
                    Console.WriteLine("DNS服务器地址：");
                    if (DnsCount > 0)
                    {
                        try
                        {
                            txtDNS1.Text = ip.DnsAddresses[0].ToString(); //主DNS
                            if (ip.DnsAddresses.Count > 1)
                                txtDNS2.Text = ip.DnsAddresses[1].ToString(); //备用DNS地址
                        }
                        catch(Exception er)
                        {
                            throw er;
                        }
                    }
                }
            }
        }
        #endregion

        #region 判断是否是正确的ip地址
        /// <summary>
        /// 判断是否是正确的ip地址
        /// </summary>
        /// <param name="ipaddress"></param>
        /// <returns></returns>
        protected bool IsIpaddress(string ipaddress)
        {
            string[] nums = ipaddress.Split('.');
            if (nums.Length != 4) return false;
            foreach (string num in nums)
            {
                if (Convert.ToInt32(num) < 0 || Convert.ToInt32(num) > 255) return false;
            }
            return true;
        }
        #endregion

        #region Form1_Load
        private void Form1_Load(object sender, EventArgs e)
        {
            loadConfig();
        }
        #endregion

    }
}
